package com.algo.pattern.command.command;

import com.algo.pattern.command.constants.OpenApiConfig;
import com.algo.pattern.command.sign.SignHelper;
import com.algo.pattern.command.util.HttpClient;
import com.algo.pattern.command.util.ParamBuilder;

import java.util.Map;

/**
 * 抽象美团请求命令接口
 * @param <Q>
 * @param <R>
 */
public abstract class AbstractMeituanRequestCommand<Q, R> implements MeituanRequestCommand<Q, R> {

    /**
     * 发送美团请求
     * @param requestParam
     * @return
     */
    @Override
    public R sendRequest(Q requestParam) throws Exception {
        String appkey = OpenApiConfig.TEST_APP_KEY;
        String secret = OpenApiConfig.TEST_SECRET;

        Map<String, String> params = ParamBuilder.convertToMap(requestParam);
        String sign = SignHelper.generateSign(params, secret);

        params.put("sign", sign);

        try {
            String res = HttpClient.post(getMethodName(), params);
            System.out.println(String.format("reponse data: %s", res));
            // 处理结果集
            return handleResponse(res);
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * 响应结果处理
     * @return
     */
    protected abstract R handleResponse(String response);

    /**
     * 子类实现，返回美团请求的 uri
     * @return
     */
    protected abstract String getMethodName();

}
